//
//  EveryTypeController.m
//  HappyBaby
//
//  Created by 华哥 on 15/11/25.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "EveryTypeController.h"
#import "ChildrenStoryTableCell.h"
#import "Define.h"
#import "VideoPlayer.h"
#import "ChildrenStoryInterface.h"
#import "SqliteManager.h"
#import "MJRefresh.h"

@interface EveryTypeController () <UITableViewDataSource, UITableViewDelegate, AVAudioPlayerDelegate, VideoProgress>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) VideoPlayer *player;
@property (nonatomic, strong) NSMutableArray *modelArray;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) BOOL isClick;
@property (nonatomic, assign) NSInteger isPlayingModel;

// 判断现在加载到第几页;
@property (nonatomic, assign) NSInteger page;

@end

@implementation EveryTypeController

- (NSMutableArray *)modelArray
{
    if (_modelArray == nil)
    {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (void)dealloc
{

}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isPlayingModel = INT32_MAX;
    self.navigationController.navigationBar.translucent = NO;
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(barButtonAction:)];
    
    self.navigationItem.title = self.listModel.name;
    
    self.navigationItem.leftBarButtonItem = leftBarButton;    
    [self analyseWithURL:self.url];
    [self creatView];
    

    //    上拉加载更多方法;
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerRefreshing)];
    //    下拉刷新方法
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerRefreshing)];
    
}

- (void)creatView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth, (kScreenHeight) *kScreenHeight / 667) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor redColor];
    [self.tableView registerClass:[ChildrenStoryTableCell class] forCellReuseIdentifier:@"tableViewCell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = NO;
    self.tableView.backgroundColor = [UIColor colorWithRed:184 / 255.0 green:241 / 255.0 blue:251 / 255.0 alpha:1];
    [self.view addSubview:_tableView];
    
    self.player = [[VideoPlayer alloc]initWithFrame:CGRectMake(0, (kScreenHeight - 49 - 64)  - 60 * kScreenHeight / 667, kScreenWidth, 60 * kScreenHeight / 667)];
    self.player.layer.cornerRadius = 5;
    [self.view addSubview:_player];
    self.player.videoProgress.delegate = self;
    self.player.backgroundColor = [UIColor colorWithRed:251 / 255.0 green:247 / 255.0 blue:219 / 255.0 alpha:1];
    
//    分别跟自定义的Progress上的控件添加方法
    [self.player.videoProgress.slider addTarget:self action:@selector(valueChanger:other:) forControlEvents:UIControlEventValueChanged];
    [self.player.nextButon addTarget:self action:@selector(nextButonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.player.beforeButton addTarget:self action:@selector(beforeButonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.player.playAndPause addTarget:self action:@selector(playAndPauseAction:) forControlEvents:UIControlEventTouchUpInside];   
}

#pragma mark ---------------------- tableView 设置 -----------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.modelArray.count == 0)
    {
        return 0;
    }
    return self.modelArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60 * kScreenHeight / 667;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildrenStoryTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell" forIndexPath:indexPath];
    cell.orderLabel.text = [NSString stringWithFormat:@"%ld",indexPath.row + 1];
    cell.model = self.modelArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChildrenStoryInterface *childModel = self.modelArray[indexPath.row];
    self.player.namelabel.text = childModel.name;
    [self playWithModel:childModel];
    self.isPlayingModel = (NSInteger)indexPath.row;
    self.isClick = YES;
}

- (void)playWithModel:(ChildrenStoryInterface *)model
{
    SqliteManager *sql = [SqliteManager shareInstance];
    ChildrenStoryInterface *selectModel = [sql selectOneDataWithTableName:@"HappyBaby" downurl:model.downurl];
    if (selectModel.downurl != nil)
    {
        NSURL *selectFileUrl = [NSURL fileURLWithPath:model.savePath];
        self.player.avAudioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:selectFileUrl error:nil];
        [self.player.avAudioPlayer play];
        [self.player.playAndPause setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
        self.player.namelabel.text = model.name;
        //    添加一个定时器
        self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    else
    {
    NSURL *url = [NSURL URLWithString:model.downurl];
    NSData *data = [NSData dataWithContentsOfURL:url];
        NSLog(@"%@",url);
    //    将数据保存到本地
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.mp4",docPath,model.name];
    [data writeToFile:filePath atomically:YES];
    //    播放本地音乐
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    self.player.avAudioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:nil];
    
    [self.player.avAudioPlayer play];
    [self.player.playAndPause setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
    self.player.namelabel.text = model.name;
    //    添加一个定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [sql insertDataWithTableName:@"HappyBaby" childrenStoryDetail:model];
    }
}

#pragma mark ------------------------- 播放切换相关 -----------------------------------
- (void)nextButonAction:(UIButton *)button
{
    if (self.isPlayingModel != INT32_MAX) {
        self.isPlayingModel += 1;
        ChildrenStoryInterface *model = self.modelArray[_isPlayingModel];
        [self playWithModel:model];
    }
}
- (void)beforeButonAction:(UIButton *)button
{
    if (self.isPlayingModel != INT32_MAX)
    {
        self.isPlayingModel -= 1;
        ChildrenStoryInterface *model = self.modelArray[_isPlayingModel];
        [self playWithModel:model];
    }
}
#pragma mark ---------------- Progress相关 -------------------
- (void)timerAction
{
    if (self.player.videoProgress.slider.highlighted == NO)
    {
        self.player.videoProgress.cache = self.player.avAudioPlayer.currentTime / self.player.avAudioPlayer.duration;
        self.player.videoProgress.slider.value = self.player.avAudioPlayer.currentTime / self.player.avAudioPlayer.duration;
        self.player.timeLabel.text = [NSString stringWithFormat:@"%.02d : %.02d",(int)self.player.avAudioPlayer.currentTime / 60, (int)self.player.avAudioPlayer.currentTime % 60];
        
//        结束时候播放下一首
        if ((self.player.avAudioPlayer.duration - self.player.avAudioPlayer.currentTime) < 1) {
            _isPlayingModel += 1;
            ChildrenStoryInterface *model = self.modelArray[_isPlayingModel];
            [self playWithModel:model];
        }
    }
}

- (void)touchView:(float)value
{
    self.player.avAudioPlayer.currentTime = value * self.player.avAudioPlayer.duration;
    self.player.videoProgress.slider.value = value;
}

- (void)valueChanger:(UISlider *)slider other:(UIEvent *)event
{
    if (self.isPlayingModel != INT32_MAX)
    {
        UITouch *touch = [[event allTouches]anyObject];
        switch (touch.phase) {
            case UITouchPhaseBegan:
            {
                break;
            }
            case UITouchPhaseMoved:
            {
                break;
            }
            case UITouchPhaseEnded:
            {
                self.player.avAudioPlayer.currentTime = self.player.videoProgress.slider.value * self.player.avAudioPlayer.duration;
                //            self.player.videoProgress.slider.value = slider.value;
                break;
            }
            default:
                break;
        }
    }
}

- (void)playAndPauseAction:(UIButton *)button
{
    if (_isClick)
    {
        if (self.player.avAudioPlayer.isPlaying)
        {
            [self.player.avAudioPlayer pause];
            [self.player.playAndPause setImage:[UIImage imageNamed:@"iconfont-bofang"] forState:UIControlStateNormal];
        }
        else
        {
            [self.player.avAudioPlayer play];
            [self.player.playAndPause setImage:[UIImage imageNamed:@"iconfont-zanting"] forState:UIControlStateNormal];
        }
    }
}

- (void)analyseWithURL:(NSString *)url
{
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *array = [dic objectForKey:@"list"];
        
        for (int i = 1; i < array.count; i++)
        {
            NSDictionary *smallDic = array[i];
            ChildrenStoryInterface *model = [[ChildrenStoryInterface alloc]init];
            [model setValuesForKeysWithDictionary:smallDic];
            [self.modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            self.page = 0;
        });
    }]resume];
}

- (void)barButtonAction:(UIBarButtonItem *)barButton
{
//    先停止在滞空, 否则容易BUG;
    if (self.isPlayingModel != INT32_MAX)
    {
        [self.player.avAudioPlayer stop];
        self.player = nil;
    }
    [self.timer invalidate];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark --------------------- 加载 / 刷新的执行方法 ------------
- (void)footerRefreshing
{
    NSString *url = [NSString stringWithFormat:@"http://bb.shoujiduoduo.com/baby/bb.php?type=getlist&page=%ld&pagesize=30&listid=%@",(long)self.page,self.listModel.myID];
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *array = [dic objectForKey:@"list"];
        
        for (int i = 1; i < array.count; i++)
        {
            NSDictionary *smallDic = array[i];
            ChildrenStoryInterface *model = [[ChildrenStoryInterface alloc]init];
            [model setValuesForKeysWithDictionary:smallDic];
            [self.modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [self.tableView.footer endRefreshing];
            self.page += 1;
        });
    }]resume];
}
- (void)headerRefreshing
{
    [self performSelector:@selector(headerRefreshingEnd) withObject:nil afterDelay:1];
}
- (void)headerRefreshingEnd
{
    [self.tableView.header endRefreshing];
}

@end
